package net.midnighttd.game;

import net.midnighttd.game.entity.Unit;
import net.midnighttd.engine.entity.Entity;
import net.midnighttd.engine.Engine;

import java.util.LinkedList;

import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

/**
 * Author: Adam Scarr
 * Date: 20/04/2009
 * Time: 10:19:34 AM
 */
public class Wave {
    private int duration;
    private int delay;
    private int curCreep = 0;
    private Spawn spawn;
    private Engine game;
    private LinkedList<String> creepList = new LinkedList<String>();
    private static final long second = 1000000000l;

    public Wave(Engine game, Spawn spawn, Element waveElement) {
        duration = Integer.valueOf(waveElement.getAttribute("duration"));
        delay = Integer.valueOf(waveElement.getAttribute("delay"));
        this.spawn = spawn;
        this.game = game;

        NodeList creeps = waveElement.getElementsByTagName("creep");

        for(int i = 0; i < creeps.getLength(); i++) {
            if(creeps.item(i).getNodeType() != Node.ELEMENT_NODE) continue;
            org.w3c.dom.Element creep = (org.w3c.dom.Element)creeps.item(i);

            int creepQty = Integer.valueOf(creep.getAttribute("qty"));

            for(int j = 0; j <= creepQty; j++) {
                creepList.add(creep.getAttribute("name"));
            }
        }
    }
    
    public long getDuration() {
        return duration * second;
    }

    public long getDelay() {
        return delay * second;
    }

    public LinkedList<Entity> getSpawn(long timeSinceStart, long spawnDuration) {
        if(creepList.size() == 0) return new LinkedList<Entity>();
        long nanosecondsPerCreep = duration * second / creepList.size();

        int nextSpawn = curCreep + 1;
        long timeToNextCreep = nextSpawn * nanosecondsPerCreep - timeSinceStart;

        LinkedList<Entity> spawn = new LinkedList<Entity>();

        while(timeToNextCreep < 0 && (curCreep + 1) < creepList.size()) {
            curCreep++;
            Unit unit = (Unit)game.getEntityManager().createEntity(creepList.get(curCreep));
            unit.setLocation(this.spawn.getStart().x, this.spawn.getStart().y);
            unit.moveTo(this.spawn.getEnd().x,  this.spawn.getEnd().y);
            spawn.add(unit);
            timeToNextCreep += nanosecondsPerCreep;
        }

        return spawn;
    }
}
